import { getBookList } from '../utils/api'
export const state = () => {
  return {
    loading: false,
    success: true,
    bookList: {
      left: [],
      right: []
    },
    page: 1,
    hasMore: true
  }
};

export const getters = {
  getBookList: state => state.bookList,
  getBookListSuccess: state => state.success,
  getBookListLoading: state => state.loading,
  getBookListPage: state => state.page,
  getBookListHasMore: state => state.hasMore
};

export const actions = {
  async getBook ({ commit }, page) {
    commit('REQUEST_BOOK_LIST');
    await getBookList({
      page
    }).then((res) => {
      if (res.code === 1) {
        commit('BOOK_LIST', res.data);
      }
    }, err => {
      commit('REQUEST_BOOK_LIST_FAILURE');
    })
  }
}

export const mutations = {
  REQUEST_BOOK_LIST (state) {
    state.loading = true;
  },
  BOOK_LIST (state, data) {
    state.loading = false;
    for (let i = 0; i < data.data.length / 2; i++) {
      state.bookList.left.push(data.data[i]);
    }
    for (let index = data.data.length / 2 - 1; index < data.data.length; index++) {
      console.log(index);
      state.bookList.right.push(data.data[index]);
    }
    console.log(state.bookList);
    state.hasMore = (data.page.total > data.page.current_page * data.page.per_page);
  },
  REQUEST_BOOK_LIST_FAILURE (state) {
    state.loading = false;
    state.success = false;
  }
}
